/**
 * Project Name:ulewo-web
 * File Name:CommentController.java
 * Package Name:com.ulewo.controller
 * Date:2015年11月2日下午9:30:38
 * Copyright (c) 2015, ulewo.com All Rights Reserved.
 */

package com.ulewo.api.controller;

import com.ulewo.controller.BaseController;
import com.ulewo.exception.BusinessException;
import com.ulewo.po.config.ConfigInfo;
import com.ulewo.po.enums.ResponseCode;
import com.ulewo.po.model.SessionUser;
import com.ulewo.po.vo.AjaxResponse;
import com.ulewo.po.vo.api.UserLoginInfoVO;
import com.ulewo.service.UserService;
import com.ulewo.utils.Constants;
import com.ulewo.utils.ServerUtils;
import com.ulewo.utils.StringTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api")
public class ApiLoginController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(ApiLoginController.class);

    private static final String LOGGER_PREFIX_LOGIN = "api登录";

    private static final String LOGGER_PREFIX_RECAPTURETOKEN = "api重新获取token";

    private static final String LOGGER_PREFIX_CHECK_UPDATE = "获取版本信息";

    @Resource
    private UserService userService;

    @Resource
    private ConfigInfo configInfo;

    /**
     * 登录
     * @param account
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping("login")
    public AjaxResponse<UserLoginInfoVO> login(String account, String password) {
        AjaxResponse<UserLoginInfoVO> result = new AjaxResponse<>();
        result.setResponseCode(ResponseCode.SUCCESS);
        try {
            UserLoginInfoVO vo = userService.login4Api(account, password);
            result.setData(vo);
        } catch (BusinessException e) {
            logger.error("{}，业务异常", LOGGER_PREFIX_LOGIN, e);
            result.setResponseCode(ResponseCode.BUSINESSERROR);
            result.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("系统异常");
            logger.error("{}，系统异常", LOGGER_PREFIX_LOGIN, e);
        }
        return result;
    }

    /**
     * 重新获取token
     * @param userId
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping("recaptureToken")
    public AjaxResponse<String> recaptureToken(String userId, String password) {
        logger.info("token失效重新获取token,userId:{},password:{}", userId, password);
        AjaxResponse<String> result = new AjaxResponse<>();
        result.setResponseCode(ResponseCode.SUCCESS);
        try {
            String token = userService.recaptureToken(userId, password);
            result.setData(token);
        } catch (BusinessException e) {
            logger.error("{}，业务异常", LOGGER_PREFIX_RECAPTURETOKEN, e);
            result.setResponseCode(ResponseCode.BUSINESSERROR);
            result.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("系统异常");
            logger.error("{}，系统异常", LOGGER_PREFIX_RECAPTURETOKEN, e);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "base64AvatarUpload.action")
    public AjaxResponse<String> base64ImageUpload(HttpSession session, String base64Image) {
        AjaxResponse<String> result = new AjaxResponse<>();
        OutputStream out = null;
        try {
            String realPath = ServerUtils.getImageFolder();

            if (StringTools.isEmpty(base64Image)) {//图像数据为空
                result.setResponseCode(ResponseCode.BUSINESSERROR);
                result.setErrorMsg("图片base64编码不能为空");
                return result;
            }
            base64Image = base64Image.replace("data:image/jpeg;base64,", "");

            BASE64Decoder decoder = new BASE64Decoder();
            //Base64解码
            byte[] b = decoder.decodeBuffer(base64Image);

            if (b.length > Constants.SIZE_1_M) {
                result.setResponseCode(ResponseCode.BUSINESSERROR);
                result.setErrorMsg("图片不能超过1M");
                return result;
            }

            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }

            SessionUser sessionUser = this.getSessionUser(session);

            //生成jpeg图片
            String fileName = sessionUser.getUserId() + ".jpg";
            String savePath = Constants.PATH_AVATARS + fileName;
            String fileDir = realPath + Constants.PATH_AVATARS;
            File dir = new File(fileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String filePath = fileDir + "/" + fileName;
            out = new FileOutputStream(filePath);
            out.write(b);
            out.flush();
            result.setResponseCode(ResponseCode.SUCCESS);
            result.setData(savePath);
            return result;
        } catch (Exception e) {
            logger.error("图片上传异常", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("图片上传异常");
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("checkUpdate")
    public AjaxResponse<Map<String, Object>> checkUpdate(String version, String client) {
        logger.info("{} 请求参数信息：version{}，client{}", LOGGER_PREFIX_CHECK_UPDATE, version, client);
        AjaxResponse<Map<String, Object>> result = new AjaxResponse<>();
        result.setResponseCode(ResponseCode.SUCCESS);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("status", 0);
        try {
            if (StringUtils.isEmpty(version) || StringUtils.isEmpty(client)) {
                throw new BusinessException("请求参数不正确");
            }
            String serverVer = configInfo.getApiUpdateAndroidVersion();
            String serverDesc = configInfo.getApiUpdateAndroidDesc();
            if ("android".equalsIgnoreCase(client)) {
                int serverVerInt = Integer.parseInt(serverVer.replace(".", ""));
                int clientVerInt = Integer.parseInt(version.replace(".", ""));
                if (serverVerInt > clientVerInt) {
                    resultMap.put("status", 1);
                    resultMap.put("serverVersion", serverVer);
                    resultMap.put("updateDesc", serverDesc);
                }
            }
            result.setData(resultMap);
        } catch (BusinessException e) {
            logger.error("{}，业务异常", LOGGER_PREFIX_CHECK_UPDATE, e);
            result.setResponseCode(ResponseCode.BUSINESSERROR);
            result.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("系统异常");
            logger.error("{}，系统异常", LOGGER_PREFIX_CHECK_UPDATE, e);
        }
        return result;
    }
}
